import React, { Component } from 'react';
import { Dispatch } from 'redux';

import _ from 'lodash';

import { inputNumber } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
    Card,
    Row,
    Col,
    Button,
    Table,
    Modal,
    Badge,
    Input,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import BindCabinet from './bindModal';

const { Item } = Form;
const { confirm } = Modal;

interface bindCabinetProps extends FormComponentProps {
    dispatch: Dispatch<any>;
    loading: any;
    allCabinetLoading: any;
    searchValues: any;
    tabIndex: string;
    pageIndex: any;
    pageSize: any;
    cabinetList: any;
    INITINFO: any;
    cabinetAllList: any;
    changeQuery: (obj: any) => void
}

interface bindCabinetState {
    visible: boolean;
}

class BindCabinetElem extends Component<bindCabinetProps, bindCabinetState> {
    columns = [{
        title: '柜体名称',
        dataIndex: 'cabName',
    }, {
        title: '柜体编号',
        dataIndex: 'cabCode',
    }, {
        title: '连接状态',
        dataIndex: 'linkStatus',
        render: (text: any) => (
            <>
                {text === '在线' && (
                    <Badge status="success" text="在线" />
                )}
                {text !== '在线' && (
                    <Badge status="default" text="离线" />
                )}
            </>
        ),
    }, {
        title: '操作',
        dataIndex: 'id',
        render: (text: any, record: any) => (
            <span
                style={{ color: '#1890ff', cursor: 'pointer' }}
                onClick={() => this.unbundle(record)}
            >解绑
            </span>
        ),
    }]

    state: bindCabinetState = {
        visible: false,
    }

    timer: any = null

    componentDidMount() {
        this.setFieldsValue();
        this.fetchList();
    }

    componentDidUpdate(prevProps: any, prevState: any) {
        const {
            searchValues, pageIndex, pageSize,
        } = this.props;
        if (!_.isEqual(searchValues, prevProps.searchValues)
            || pageIndex !== prevProps.pageIndex
            || pageSize !== prevProps.pageSize
        ) {
            this.setFieldsValue();
            this.fetchList();
        }
    }

    // 设置表单值
    setFieldsValue = () => {
        const { searchValues } = this.props;
        const { form: { setFieldsValue } } = this.props;
        setFieldsValue(searchValues);
    }

    // 获取绑定柜体列表
    fetchList = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'tencentConfig/fetchCabinetList',
            payload: this.getQueryParams(),
        });
    }

    // 获取参数
    getQueryParams = () => {
        const { pageSize, pageIndex, searchValues } = this.props;
        return {
            pageSize,
            pageIndex,
            ...searchValues,
        };
    }

    // 查询柜体
    searchCabinet = (name: string = '') => {
        if (name) {
            clearTimeout(this.timer);

            const { dispatch } = this.props;
            this.timer = setTimeout(() => {
                dispatch({
                    type: 'common/fetchCabinetList',
                    payload: { name },
                });
            }, 500);
        }
    };

    // 监听用户手机号输入
    changeCode = (e: any) => {
        const value = inputNumber(e);

        const { form: { setFieldsValue } } = this.props;
        setTimeout(() => {
            setFieldsValue({ cabCode: value });
        }, 0);
    }

    // 查询
    handleSearch = (e: React.FormEvent) => {
        e.preventDefault();

        const { form: { validateFields }, pageSize } = this.props;
        validateFields((errors: any, fieldsValue: any) => {
            if (errors) return;

            this.commonQuery(fieldsValue, 1, pageSize);
        });
    }

    // 重置
    handleFormReset = () => {
        const {
            form: { resetFields }, pageSize,
        } = this.props;
        resetFields();

        this.commonQuery({}, 1, pageSize);
    }

    // 切换页码
    onSelectChange = (page: number, psize: number | undefined) => {
        const { searchValues } = this.props;

        this.commonQuery(searchValues, page, psize);
    }

    commonQuery = (searchValues: any, pageIndex: any, pageSize: any) => {
        const { changeQuery, tabIndex } = this.props;

        const query = {
            pageSize,
            pageIndex,
            tab: tabIndex,
            ...searchValues,
        };

        changeQuery(query);
    }

    // 解绑
    unbundle = ({ id, cabName, cabCode }: any) => {
        const { dispatch } = this.props;
        const search = this.getQueryParams();
        confirm({
            title: '解绑柜体确认',
            content: `确认解除【${cabName}】【${cabCode}】的柜体？解除后该柜体的订单将不再通过您公众号发送消息通知！`,
            okText: '确认',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'tencentConfig/fetchUnbind',
                    payload: { id, search, type: 1 },
                });
            },
        });
    }

    // 绑定柜体
    bindCabinet = (visible: boolean, pageIndex?: any, pageSize?: any) => {
        this.setState({ visible });

        const { dispatch } = this.props;
        if (visible) {
            dispatch({
                type: 'tencentConfig/fetchAllCabinet',
                payload: {
                    pageSize: pageSize || 10,
                    pageIndex: pageIndex || 1,
                },
            });
        } else {
            dispatch({ type: 'tencentConfig/clear' });
        }
    }

    render() {
        const {
            dispatch,
            pageSize,
            pageIndex,
            cabinetList,
            cabinetAllList,
            loading,
            allCabinetLoading,
            form: { getFieldDecorator },
        } = this.props;

        const { visible } = this.state;
        const pagination = cabinetList
            ? {
                total: cabinetList.count,
                pageSize: Number(pageSize),
                current: Number(pageIndex),
                showQuickJumper: true,
                showSizeChanger: true,
                pageSizeOptions: ['10', '20', '50', '100'],
                showTotal: () => `共${cabinetList.count}条数据`,
                onChange: this.onSelectChange,
                onShowSizeChange: this.onSelectChange,
            }
            : {};

        return (
            <>
                <Card bordered={false} className="noMarginLeft">
                    <Form onSubmit={this.handleSearch} className="tableListForm">
                        <Row gutter={12}>
                            <Col md={8} sm={24}>
                                <Item label="柜体名称" colon={false}>
                                    {getFieldDecorator('cabName')(
                                        <Input
                                            allowClear
                                            autoComplete="off"
                                            placeholder="请输入柜体名称"
                                        />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={8} sm={24}>
                                <Item label="柜体编号" colon={false}>
                                    {getFieldDecorator('cabCode')(
                                        <Input
                                            allowClear
                                            maxLength={15}
                                            placeholder="请输入柜体编号"
                                            autoComplete="off"
                                            onChange={this.changeCode}
                                        />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={8} sm={24}>
                                <div className="flexFeView" style={{ margin: '0 0 20px 0' }}>
                                    <Button
                                        type="primary"
                                        htmlType="submit"
                                        className="smallButton"
                                    >
                                        查询
                                    </Button>
                                    <Button
                                        type="primary"
                                        className="addButton marginL16 smallButton"
                                        onClick={this.handleFormReset}
                                    >
                                        重置
                                    </Button>
                                </div>
                            </Col>
                        </Row>
                    </Form>

                    <Button type="primary" onClick={() => this.bindCabinet(true)}>绑定柜体</Button>
                    <Table
                        rowKey="id"
                        columns={this.columns}
                        dataSource={cabinetList.list}
                        pagination={pagination}
                        style={{ marginTop: '16px' }}
                        loading={loading}
                    />
                </Card>

                <BindCabinet
                    visible={visible}
                    loading={allCabinetLoading}
                    dispatch={dispatch}
                    search={this.getQueryParams()}
                    cabinetAllList={cabinetAllList}
                    bindCabinet={this.bindCabinet}
                    type={1}
                />
            </>
        );
    }
}

export default Form.create<bindCabinetProps>()(BindCabinetElem);
